package com.agile.ecloud.sdk.test;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.text.SimpleDateFormat;
import java.util.*;

public class MakeH5Url {

    //appKey、secrept和 aesKey 均在开放平台的产品列表中查询
    protected String appKey = "xxx";
    protected String secrept = "xxx";
    protected String aesKey = "xxx";

    String h5url = "https://fat-yss-h5.myrrx.com/signFilePage";//测试环境
    //String h5url = "https://h5.ecloudsign.com/signFilePage";//正式环境

    //生成发起页H5链接
    public String mkSimpleUrl(String telephone, String contractNum,
                              List<String> signPosition, String cardType, String idCardNum, String name, String isFinish,
                              String callBack, String wxCallBack, int signType, boolean smscode
    ) throws Exception {

        Map<String, String> map = new HashMap<>();
        map.put("secret", secrept);
        map.put("v", "1.0");
        map.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        map.put("telephone", telephone);
        map.put("contractNum", contractNum);
        map.put("cardType", cardType);
        map.put("idCardNum", idCardNum);
        map.put("name", name);
        map.put("isFinish", isFinish);
        map.put("signPosition", JSONObject.toJSONString(signPosition));

        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> en : map.entrySet()) {
            if (sb.length() == 0) {
                sb.append(String.format("%s=%s", en.getKey(), aesEncrypt(en.getValue(), aesKey)));
            } else {
                sb.append(String.format("&%s=%s", en.getKey(), aesEncrypt(en.getValue(), aesKey)));
            }
        }
        sb.append(String.format("&%s=%s", "appKey", appKey));
        sb.append(String.format("&%s=%s", "callBack", callBack));
        sb.append(String.format("&%s=%s", "wxCallBack", wxCallBack));
        sb.append(String.format("&%s=%s", "signType", signType));
        sb.append(String.format("&%s=%s", "smscode", smscode));
        return h5url + "?"+ sb.toString();
    }

    /**
     * 加密参数方法
     * @param str
     * @param key
     * @return
     * @throws Exception
     */
    public  String aesEncrypt(String str, String key) throws Exception {
        if (str == null || key == null) {
            return null;
        }
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
        byte[] bytes = cipher.doFinal(str.getBytes("utf-8"));
        return Base64.encodeBase64String(bytes);
    }
}
